import { defineStore } from 'pinia'

import { RouteRecordRaw } from 'vue-router'
import { Userinfo, ListAdminMenu } from '@/api/index'
import { ReadConfig } from '@/api/admin_config'
import { iPb } from '@/protobuf/interface/index'
import { ref } from 'vue'
import { SetToken } from '@/tool/common'

const Layout = () => import("@/layout/index.vue")

const modules = import.meta.glob('@/views/**/*.vue')

const ViewModules = new Map()

for(let i in modules) {
    let path = i.replace('/src/views/','').replace('.vue','')
    ViewModules.set(path,modules[i])
}

export const useStore: any = defineStore("pinia", {
    state: () => {
        const userinfo = ref<iPb.Admin.IUserinfoResponse>(iPb.Admin.UserinfoResponse.create())
        const ListMenu = ref<RouteRecordRaw[]>([])
        const Auth = ref<string[]>([])
        const Config = ref<iPb.IDbConfig>(iPb.DbConfig.create())
        const IsInit = ref<Boolean>(false)
        return {
            userinfo: userinfo.value,
            ListMenu: ListMenu.value,
            Auth: Auth.value,
            Config: Config.value,
            IsInit: IsInit.value
        }
    },
    getters: {},
    actions: {
        logout() {
            let _this = this
            SetToken("")
            _this.userinfo = iPb.Admin.UserinfoResponse.create()
            _this.ListMenu = []
            _this.Auth = []
            _this.Config = iPb.DbConfig.create()
            _this.IsInit = false
        },
        login(token: string) {
            SetToken(token)
        },
        initUserinfo() {
            let _this = this
            return new Promise( resolve => {
                if (!Object.keys(_this.userinfo).length || _this.userinfo.account == "") {
                    Userinfo().then((result:iPb.Admin.IUserinfoResponse) => {
                        let userinfo = iPb.Admin.UserinfoResponse.create(result)
                        _this.userinfo = userinfo
                        let m = filterAsyncRouter(userinfo.menu)
                        const routes: Array<RouteRecordRaw> = [
                            {
                                path: '/',
                                component: Layout,
                                redirect: m[0].path,
                                children: m
                            },
                        ]
                        _this.Auth = userinfo.auth
                        resolve(routes)
                    })
                }else {
                    resolve(_this.ListMenu)
                }
            })
        },
        initListMenu(data?: iPb.Admin.IListAdminMenuRequest) {
            let _this = this
            return new Promise( resolve => {
                let formData = iPb.Admin.ListAdminMenuRequest.toObject(iPb.Admin.ListAdminMenuRequest.create(data))
                ListAdminMenu(formData).then((result:iPb.Admin.IListAdminMenuResponse) => {
                    let R = iPb.Admin.ListAdminMenuResponse.create(result)
                    if(R.count > 0) {
                        let m = filterAsyncRouter(R.data)
                        const routes: Array<RouteRecordRaw> = [
                            {
                                path: '/',
                                component: Layout,
                                redirect: m[0].path,
                                children: m
                            },
                        ]
                        _this.ListMenu = routes
                        _this.Auth = R.auth
                    }
                    resolve(_this.ListMenu)
                })
            })
        },
        initConfig() {
            let _this = this
            ReadConfig().then((result:iPb.IDbConfig) => {
                let r = iPb.DbConfig.create(result)
                _this.Config = r
            })
        },
        init() {
            let _this = this
            if(_this.IsInit) { // 保证只执行一次
                return
            }
            _this.IsInit = true
            _this.initConfig()
        },
    }
})


function filterAsyncRouter(menu: iPb.IDbAdminMenu[]): RouteRecordRaw[] {
    return menu.map((item:iPb.IDbAdminMenu):RouteRecordRaw => {
        let obj:RouteRecordRaw = {
            path: `/${item.route}`,
            name: item.route || "",
            meta: {
                title: `${item.title}`,
                type: item.type || 0,
                icon: item.icon || "",
                is_show: item.display || 0,
                state: item.state || 0,
                id: item.id,
                pid: item.pid || 0,
                level: item.level || 0,
                translate_key: item.translate_key || 0
            },
            children: []
        }
        if(item.component) {
            obj.component = ViewModules.get(item.component)
        }
        if(item.children && item.children.length > 0) {
            let children:iPb.IDbAdminMenu[] = []
            for(let i in item.children) {
                children.push(item.children[i])
            }
            obj.children = filterAsyncRouter(children)
        }
        return obj
    })
}